<template>
  <div class="product-barcode-page">
    <el-card class="barcode-card">
      <template #header>
        <div class="card-header">
          <span>条码管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增条码</el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">批量删除</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable/>
          </el-form-item>
          <el-form-item label="条码">
            <el-input v-model="searchForm.barcode" placeholder="请输入条码" clearable/>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" :value="1"/>
              <el-option label="禁用" :value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格 -->
      <el-table
        :data="dataList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="productName" label="商品名称" width="150"/>
        <el-table-column prop="productCode" label="商品编码" width="120"/>
        <el-table-column prop="barcode" label="条码" width="150"/>
        <el-table-column prop="barcodeType" label="条码类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.barcodeType === 1 ? 'primary' : 'success'">
              {{ scope.row.barcodeType === 1 ? '一维码' : '二维码' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="条码图片" width="120">
          <template #default="scope">
            <el-button size="small" @click="handlePreviewBarcode(scope.row)">预览</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="baseUnitName" label="基本单位" width="100"/>
        <el-table-column prop="subUnitName" label="副单位" width="100"/>
        <el-table-column prop="conversionRatio" label="换算比例" width="100"/>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="150">
          <template #default="scope">
            {{ scope.row.remark || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
              </el-table>
        
        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="120px">
        <el-form-item label="商品" prop="productId">
          <el-select
            v-model="formData.productId"
            placeholder="请选择商品"
            filterable
            remote
            :remote-method="handleProductSearch"
            :loading="productLoading">
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.productName"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="条码" prop="barcode">
          <el-input v-model="formData.barcode" placeholder="请输入条码"/>
        </el-form-item>
        <el-form-item label="条码类型" prop="barcodeType">
          <el-radio-group v-model="formData.barcodeType">
            <el-radio :label="1">一维码</el-radio>
            <el-radio :label="2">二维码</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="基本单位" prop="baseUnitId">
          <el-select v-model="formData.baseUnitId" placeholder="请选择基本单位">
            <el-option
              v-for="item in unitOptions"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="副单位" prop="subUnitId">
          <el-select v-model="formData.subUnitId" placeholder="请选择副单位" clearable>
            <el-option
              v-for="item in unitOptions"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="换算比例" prop="conversionRatio">
          <el-input-number
            v-model="formData.conversionRatio"
            :precision="4"
            :step="0.1"
            :min="0.0001"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="条码详情" v-model="viewDialogVisible" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商品名称">{{ viewData.productName }}</el-descriptions-item>
        <el-descriptions-item label="商品编码">{{ viewData.productCode }}</el-descriptions-item>
        <el-descriptions-item label="条码">{{ viewData.barcode }}</el-descriptions-item>
        <el-descriptions-item label="条码类型">
          <el-tag :type="viewData.barcodeType === 1 ? 'primary' : 'success'">
            {{ viewData.barcodeType === 1 ? '一维码' : '二维码' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="基本单位">{{ viewData.baseUnitName }}</el-descriptions-item>
        <el-descriptions-item label="副单位">{{ viewData.subUnitName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="换算比例">{{ viewData.conversionRatio }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewData.status === 1 ? 'success' : 'danger'">
            {{ viewData.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewData.remark || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ viewData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ viewData.updateTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 条码预览对话框 -->
    <el-dialog title="条码预览" v-model="previewDialogVisible" width="500px">
      <div class="barcode-preview">
        <div class="preview-info">
          <p><strong>条码内容：</strong>{{ previewData.barcode }}</p>
          <p><strong>条码类型：</strong>
            <el-tag :type="previewData.barcodeType === 1 ? 'primary' : 'success'">
              {{ previewData.barcodeType === 1 ? '一维码' : '二维码' }}
            </el-tag>
          </p>
        </div>
        <div class="preview-image">
          <img v-if="previewImageUrl" :src="previewImageUrl" alt="条码图片"/>
          <div v-else class="loading">生成中...</div>
        </div>
        <div class="preview-actions">
          <el-button @click="handleDownloadBarcode">下载图片</el-button>
          <el-button @click="handleRegenerateBarcode">重新生成</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getBarcodeList,
  getBarcodeListPage,
  getBarcodeDetail,
  addBarcode,
  updateBarcode,
  deleteBarcode,
  deleteBarcodes,
  updateBarcodeStatus,
  generateBarcodeImage,
  generateBarcodeImageByContent,
  getAllProducts,
  getAllUnits
} from '@/api/product'

// 响应式数据
const loading = ref(false)
const dataList = ref([])
const selectedIds = ref([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const submitLoading = ref(false)
const productLoading = ref(false)
const productOptions = ref([])
const unitOptions = ref([])
const formRef = ref()
const viewData = ref({})
const previewData = ref({})
const previewImageUrl = ref('')

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  productName: '',
  barcode: '',
  status: null
})

// 表单数据
const formData = reactive({
  id: null,
  productId: null,
  barcode: '',
  barcodeType: 1,
  baseUnitId: null,
  subUnitId: null,
  conversionRatio: 1,
  status: 1,
  remark: ''
})

// 表单验证规则
const formRules = {
  productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
  barcode: [{ required: true, message: '请输入条码', trigger: 'blur' }],
  barcodeType: [{ required: true, message: '请选择条码类型', trigger: 'change' }],
  baseUnitId: [{ required: true, message: '请选择基本单位', trigger: 'change' }],
  conversionRatio: [{ required: true, message: '请输入换算比例', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 计算属性
const dialogTitle = computed(() => formData.id ? '编辑条码' : '新增条码')

// 方法
const loadData = async() => {
  loading.value = true
  try {
    const params = {
      productName: searchForm.productName,
      barcode: searchForm.barcode,
      status: searchForm.status,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    const res = await getBarcodeListPage(params)
    if (res.code === 200) {
      dataList.value = res.data.list
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const loadUnits = async() => {
  try {
    const res = await getAllUnits()
    if (res.code === 200) {
      unitOptions.value = res.data
    } else {
      ElMessage.error(res.message || '获取单位数据失败')
    }
  } catch (error) {
    console.error('加载单位数据失败:', error)
    ElMessage.error('加载单位数据失败')
  }
}

const handleProductSearch = async(query) => {
  if (query) {
    productLoading.value = true
    try {
      const res = await getAllProducts(query)
      if (res.code === 200) {
        productOptions.value = res.data
      } else {
        ElMessage.error(res.message || '搜索商品失败')
      }
    } catch (error) {
      console.error('搜索商品失败:', error)
      ElMessage.error('搜索商品失败')
    } finally {
      productLoading.value = false
    }
  }
}

const handleSearch = () => {
  pageNum.value = 1
  loadData()
}

const handleReset = () => {
  searchForm.productName = ''
  searchForm.barcode = ''
  searchForm.status = null
  pageNum.value = 1
  loadData()
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleView = async(row) => {
  try {
    const res = await getBarcodeDetail(row.id)
    if (res.code === 200) {
      viewData.value = res.data
      viewDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

const handleEdit = (row) => {
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = async(row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteBarcode(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 如果当前页只有一条数据且不是第一页，则跳转到上一页
      if (dataList.value.length === 1 && pageNum.value > 1) {
        pageNum.value--
      }
      loadData()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchDelete = async() => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条条码吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteBarcodes(selectedIds.value)
    if (res.code === 200) {
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      // 如果删除后当前页没有数据且不是第一页，则跳转到上一页
      if (dataList.value.length <= selectedIds.value.length && pageNum.value > 1) {
        pageNum.value--
      }
      loadData()
    } else {
      ElMessage.error(res.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const handleToggleStatus = async(row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const res = await updateBarcodeStatus(row.id, newStatus)
    if (res.code === 200) {
      ElMessage.success('状态更新成功')
      loadData()
    } else {
      ElMessage.error(res.message || '状态更新失败')
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

const handleSubmit = async() => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const api = formData.id ? updateBarcode : addBarcode
    const res = await api(formData)
    
    if (res.code === 200) {
      ElMessage.success(formData.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      loadData()
      
      // 如果是新增条码，显示预览
      if (!formData.id) {
        // 获取最新添加的条码数据
        const newBarcode = {
          id: res.data?.id || Date.now(), // 临时ID
          barcode: formData.barcode,
          barcodeType: formData.barcodeType
        }
        previewData.value = newBarcode
        previewDialogVisible.value = true
        generatePreviewImage()
      }
    } else {
      ElMessage.error(res.message || (formData.id ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    productId: null,
    barcode: '',
    barcodeType: 1,
    baseUnitId: null,
    subUnitId: null,
    conversionRatio: 1,
    status: 1,
    remark: ''
  })
  formRef.value?.resetFields()
}

const handlePreviewBarcode = (row) => {
  previewData.value = row
  previewDialogVisible.value = true
  generatePreviewImage()
}

const generatePreviewImage = () => {
  if (previewData.value.id) {
    // 根据条码ID生成图片
    const imageUrl = generateBarcodeImage(previewData.value.id, 300, 100)
    previewImageUrl.value = `http://localhost:8081${imageUrl}`
  } else {
    // 根据内容生成图片
    const imageUrl = generateBarcodeImageByContent(
      previewData.value.barcode,
      previewData.value.barcodeType,
      300,
      100
    )
    previewImageUrl.value = `http://localhost:8081${imageUrl}`
  }
}

const handleDownloadBarcode = () => {
  if (previewImageUrl.value) {
    const link = document.createElement('a')
    link.href = previewImageUrl.value
    link.download = `barcode_${previewData.value.barcode}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

const handleRegenerateBarcode = () => {
  previewImageUrl.value = ''
  setTimeout(() => {
    generatePreviewImage()
  }, 100)
}

const handlePageChange = (newPage) => {
  pageNum.value = newPage
  loadData()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  pageNum.value = 1
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
  loadUnits()
  // 初始化商品选项
  handleProductSearch('')
})
</script>

<style scoped>
.product-barcode-page {
  padding: 20px;
}

.barcode-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.barcode-preview {
  text-align: center;
}

.preview-info {
  margin-bottom: 20px;
  text-align: left;
}

.preview-info p {
  margin: 10px 0;
}

.preview-image {
  margin: 20px 0;
  min-height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-image img {
  max-width: 100%;
  max-height: 200px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.loading {
  color: #999;
  font-style: italic;
}

.preview-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
